package com.ruoyi.binding.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.binding.domain.*;
import com.ruoyi.binding.service.IMhBindingService;
import com.ruoyi.binding.service.IMhUserGameDispatchConfigService;
import com.ruoyi.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.binding.mapper.MhOrderAllocateMapper;
import com.ruoyi.binding.service.IMhOrderAllocateService;

/**
 * 订单指派Service业务层处理
 * 
 * @author Ekko
 * @date 2025-06-30
 */
@Service
@Slf4j
public class MhOrderAllocateServiceImpl implements IMhOrderAllocateService 
{
    @Autowired
    private MhOrderAllocateMapper mhOrderAllocateMapper;

    @Autowired
    private IMhBindingService mhBindingService;

    @Autowired
    private IMhUserGameDispatchConfigService iMhUserGameDispatchConfigService;



    /**
     * 计算最终订单金额
     */
    @Override
    public BigDecimal calculateFinalFee(MhBinding mhBinding, Long userId, String gameName, String fee) {
        BigDecimal adminRatio = BigDecimal.ZERO;
        if (mhBinding.getMhUserGamePriceList() != null) {
            for (MhUserGamePrice price : mhBinding.getMhUserGamePriceList()) {
                if (price.getGameCategoryName().trim().equalsIgnoreCase(gameName)) {
                    adminRatio = price.getPriceRatio();
                    break;
                }
            }
        }
        log.info("管理员抽成比例: {}%", adminRatio);

        MhUserGameDispatchConfig queryConfig = new MhUserGameDispatchConfig();
        queryConfig.setUserId(userId);
        queryConfig.setGameName(gameName);
        List<MhUserGameDispatchConfig> configList = iMhUserGameDispatchConfigService.selectConfigListNoDataScope(queryConfig);
        log.info("用户[{}] 游戏[{}] 抽成配置: {}", userId, gameName, configList);

        BigDecimal userRatio = configList.isEmpty() ? BigDecimal.ZERO : configList.get(0).getUserPriceRatio();
        log.info("用户抽成比例: {}%", userRatio);

        BigDecimal adminFactor = BigDecimal.ONE.subtract(adminRatio.divide(BigDecimal.valueOf(100)));
        BigDecimal userFactor = BigDecimal.ONE.subtract(userRatio.divide(BigDecimal.valueOf(100)));
        BigDecimal combinedFactor = adminFactor.multiply(userFactor).setScale(4, BigDecimal.ROUND_HALF_UP);
        log.info("综合抽成系数: {}", combinedFactor);

        return new BigDecimal(fee).multiply(combinedFactor).setScale(2, BigDecimal.ROUND_HALF_UP);
    }


    //获取当前用户的管理员计算抽成系数后的list
    @Override
    public List<MhOrderAllocate> resList(List<MhOrderAllocate> oList,Long userId) {
        MhBinding mhBinding = mhBindingService.selectMhBindingByUserId(userId);

        if (mhBinding == null || mhBinding.getMhUserGamePriceList() == null) {
            log.warn("用户[{}]未配置游戏比例，跳过价格计算。", userId);
            return oList;
        }

        List<MhUserGamePrice> adminRatioList = mhBinding.getMhUserGamePriceList();

        for (MhOrderAllocate o : oList) {
            String gameName = o.getGameName();
            if (gameName == null) {
                log.warn("订单[{}]无游戏名，跳过。", o.getOrderId());
                continue;
            }

            log.info("处理订单[{}] 游戏名：{} 原价：{}", o.getOrderId(), gameName, o.getPrice());

            for (MhUserGamePrice priceRatioItem : adminRatioList) {
                String ratioGameName = priceRatioItem.getGameCategoryName();
                if (ratioGameName == null) continue;

                if (ratioGameName.trim().equalsIgnoreCase(gameName.trim())) {
                    BigDecimal originalPrice = o.getPrice();
                    BigDecimal ratio = priceRatioItem.getPriceRatio();
                    if (originalPrice != null && ratio != null) {
                        BigDecimal factor = BigDecimal.ONE.subtract(ratio.divide(BigDecimal.valueOf(100)));
                        BigDecimal finalPrice = originalPrice.multiply(factor).setScale(2, BigDecimal.ROUND_HALF_UP);
                        log.info("匹配到游戏 [{}]，抽成比例：{}%，计算后价格：{}", ratioGameName, ratio, finalPrice);
                        o.setPrice(finalPrice);
                    }
                    break; // 已匹配到，不需要再循环
                }
            }
        }

        return oList;
    }

    /**
     * @param oList
     * @param userId
     * @return
     */
    @Override
    public List<MhOrderRemote> resListRemote(List<MhOrderRemote> oList, Long userId) {
        MhBinding mhBinding = mhBindingService.selectMhBindingByUserId(userId);

        if (mhBinding == null || mhBinding.getMhUserGamePriceList() == null) {
            log.warn("用户[{}]未配置游戏比例，跳过价格计算。", userId);
            return oList;
        }

        List<MhUserGamePrice> adminRatioList = mhBinding.getMhUserGamePriceList();

        for (MhOrderRemote o : oList) {
            String gameName = o.getGameName();
            if (gameName == null) {
                log.warn("订单[{}]无游戏名，跳过。", o.getOrderId());
                continue;
            }

            log.info("处理订单[{}] 游戏名：{} 原价：{}", o.getOrderId(), gameName, o.getPrice());

            for (MhUserGamePrice priceRatioItem : adminRatioList) {
                String ratioGameName = priceRatioItem.getGameCategoryName();
                if (ratioGameName == null) continue;

                if (ratioGameName.trim().equalsIgnoreCase(gameName.trim())) {
                    BigDecimal originalPrice = o.getPrice();
                    BigDecimal ratio = priceRatioItem.getPriceRatio();
                    if (originalPrice != null && ratio != null) {
                        BigDecimal factor = BigDecimal.ONE.subtract(ratio.divide(BigDecimal.valueOf(100)));
                        BigDecimal finalPrice = originalPrice.multiply(factor).setScale(2, BigDecimal.ROUND_HALF_UP);
                        log.info("匹配到游戏 [{}]，抽成比例：{}%，计算后价格：{}", ratioGameName, ratio, finalPrice);
                        o.setPrice(finalPrice);
                    }
                    break; // 已匹配到，不需要再循环
                }
            }
        }

        return oList;
    }

    /**
     * 查询订单指派
     * 
     * @param id 订单指派主键
     * @return 订单指派
     */
    @Override
    public MhOrderAllocate selectMhOrderAllocateById(String id)
    {
        return mhOrderAllocateMapper.selectMhOrderAllocateById(id);
    }

    /**
     * 查询订单指派列表
     * 
     * @param mhOrderAllocate 订单指派
     * @return 订单指派
     */
    @Override
    public List<MhOrderAllocate> selectMhOrderAllocateList(MhOrderAllocate mhOrderAllocate)
    {
        mhOrderAllocate.setIsSettStatus("未结算");
        mhOrderAllocate.setOrderSta("未分配");
        return mhOrderAllocateMapper.selectMhOrderAllocateList(mhOrderAllocate);
    }

    /**
     * 新增订单指派
     * 
     * @param mhOrderAllocate 订单指派
     * @return 结果
     */
    @Override
    public int insertMhOrderAllocate(MhOrderAllocate mhOrderAllocate)
    {
        mhOrderAllocate.setCreateTime(DateUtils.getNowDate());
        return mhOrderAllocateMapper.insertMhOrderAllocate(mhOrderAllocate);
    }

    /**
     * 修改订单指派
     * 
     * @param mhOrderAllocate 订单指派
     * @return 结果
     */
    @Override
    public int updateMhOrderAllocate(MhOrderAllocate mhOrderAllocate)
    {
        mhOrderAllocate.setUpdateTime(DateUtils.getNowDate());
        return mhOrderAllocateMapper.updateMhOrderAllocate(mhOrderAllocate);
    }

    /**
     * 批量删除订单指派
     * 
     * @param ids 需要删除的订单指派主键
     * @return 结果
     */
    @Override
    public int deleteMhOrderAllocateByIds(String[] ids)
    {
        return mhOrderAllocateMapper.deleteMhOrderAllocateByIds(ids);
    }

    /**
     * 删除订单指派信息
     * 
     * @param id 订单指派主键
     * @return 结果
     */
    @Override
    public int deleteMhOrderAllocateById(String id)
    {
        return mhOrderAllocateMapper.deleteMhOrderAllocateById(id);
    }
}
